/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.identity;

import cn.easyplatform.dao.EntityDao;
import cn.easyplatform.dao.IdentityDao;
import cn.easyplatform.dos.UserDo;
import cn.easyplatform.i18n.I18N;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.ChangePasswordRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.UserPasswordVo;
import cn.easyplatform.shiro.PasswordEncoder;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.UserType;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.AuthenticatingRealm;

import java.util.regex.Matcher;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ChangePasswordCmd extends
        AbstractCommand<ChangePasswordRequestMessage> {

    /**
     * @param req
     */
    public ChangePasswordCmd(ChangePasswordRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        UserPasswordVo pv = req.getBody();
        UserDo user = cc.getUser();
        if (user.getType() == UserType.TYPE_SUPER) {
            EntityDao dao = cc.getEngineConfiguration().getEntityDao();
            String salt = (String) dao.selectObject("SELECT salt FROM ep_user_info WHERE userId=?", pv.getOldPassword());
            String pass = cn.easyplatform.utils.SecurityUtils.getSecurePassword(pv.getNewPassword(), salt);
            cc.getEngineConfiguration().getEntityDao().update("UPDATE ep_user_info SET password=? WHERE userId=?", pass, pv.getOldPassword());
        } else {
            if (cc.getProjectService().getConfig().getCheckPasswordPattern() != null) {
                Matcher matcher = cc.getProjectService().getConfig().getCheckPasswordPattern().matcher(pv.getNewPassword());
                if (!matcher.find())
                    return new SimpleResponseMessage("E065", cc.getProjectService().getConfig().getCheckPasswordMessage());
            }
            AuthenticatingRealm realm = (AuthenticatingRealm) ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getRealms().iterator().next();
            PasswordEncoder encoder = (PasswordEncoder) realm.getCredentialsMatcher();
            String newPass = encoder.encode(pv.getNewPassword());
            String oldPass = encoder.encode(pv.getOldPassword());
            if (!user.getPassword().equals(oldPass))
                return new SimpleResponseMessage("E066",
                        I18N.getLabel("easyplatform.user.password.invalid"));
            IdentityDao dao = cc.getIdentityDao(true);
            dao.updatePassword(user.getId(), newPass);
            user.setPassword(newPass);
        }
        return new SimpleResponseMessage();
    }
}
